package com.milloc.db.common.metadata;

import com.google.common.collect.Lists;
import com.milloc.db.entity.ParameterEntity;
import lombok.extern.log4j.Log4j2;

import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.List;

/**
 * @author gongdeming
 * @create 2019-09-03
 */
@Log4j2
public class MetaDataHelper {
    private static final ThreadLocal<Boolean> START = new ThreadLocal<>();
    private static final ThreadLocal<ResultSetMetaData> METADATA = new ThreadLocal<>();

    static boolean isStart() {
        return START.get() != null && START.get();
    }

    static void add(ResultSetMetaData resultSetMetaData) {
        METADATA.set(resultSetMetaData);
    }

    public static void start() {
        START.set(true);
    }

    public static List<ParameterEntity> getParameter() {
        ResultSetMetaData resultSetMetaData = METADATA.get();
        List<ParameterEntity> res = Lists.newArrayList();
        if (resultSetMetaData != null) {
            try {
                for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
                    // TODO 添加类型判断
                    res.add(ParameterEntity.of(resultSetMetaData.getColumnName(i)));
                }
            } catch (SQLException e) {
                log.error(e);
            }
        }
        START.set(false);
        METADATA.set(null);
        return res;
    }
}
